package com.timemanage.activity

import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log


import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.loper7.date_time_picker.DateTimePicker
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.timemanage.R
import com.timemanage.dao.AppDatabase
import com.timemanage.dao.UserDao
import com.timemanage.entity.User
import com.timemanage.entity.Work
import com.timemanage.utils.MyApplication
import com.timemanage.utils.MyApplication.Companion.context
import kotlinx.android.synthetic.main.activity_sort_detail.*
import kotlinx.android.synthetic.main.sort_add.view.*
import kotlin.concurrent.thread
import com.lxj.xpopup.animator.PopupAnimator
import com.lxj.xpopup.core.CenterPopupView
import com.timemanage.activity.ui.home.HomeFragment
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.work_add.view.*
import kotlinx.android.synthetic.main.work_detail.view.*
import java.util.ArrayList





class SortDetail : AppCompatActivity() {

    var Parentid=""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sort_detail)

        Parentid = intent.getStringExtra("ID").toString()
        var sortName = ArrayList<String>()
        var sortBody = ArrayList<String>()
        var sortId   = ArrayList<String>()
        var workstartTime = ArrayList<String>()
        var workendTime   = ArrayList<String>()
            var database= AppDatabase.getDatabase(MyApplication.context)
            var workDao = database.WorkDao()
            var sortDetailList = workDao.selectSon(Parentid.toInt())
            Log.d("长度",sortDetailList.size.toString())
            Log.d("长度",(sortDetailList==null).toString())
            for (i in sortDetailList) {
                sortName.add(i.title!!)
                sortBody.add(i.workbody!!)
                sortId.add(i.workId.toString())
                if(i.startTime!=null && i.endTime!=null) {
                    workstartTime.add(i.startTime.toString())
                    workendTime.add(i.endTime.toString())
                }else{
                    workstartTime.add("no")
                    workendTime.add("no")
                }
            }

        Log.d("长度2",sortName.size.toString())
        val sortsAdapter = detailAdapter(this, sortId,sortName, sortBody,workstartTime,workendTime)
        recycleView2.adapter = sortsAdapter
        recycleView2.layoutManager = LinearLayoutManager(context)
        addSort_Button2.setOnClickListener {
            XPopup.Builder(context)
                .moveUpToKeyboard(false)
                .asCustom(addWork())
                .show();
        }
        var ab = supportActionBar
        ab?.title=intent.getStringExtra("title")
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.add_option ->{
                XPopup.Builder(context)
                    .enableDrag(true)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCustom(addSort2() /*.enableDrag(false)*/)
                    .show()
            }
            R.id.delete_option ->{
                var database= AppDatabase.getDatabase(MyApplication.context)
                var workDao = database.WorkDao()
                val tmdId:Int= (workDao.selectOneWork(Parentid.toInt())).parentId!!.toInt()
                Log.d("Parentid",Parentid)
                Log.d("tmdID",tmdId.toString())
                deleByOneId(Parentid.toInt())
                if( tmdId ==-1 ){
                    val intent = Intent(this, BottomBar::class.java)
                    intent.putExtra("id", 1)
                    startActivity(intent)
                }else{

                }
                this.finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }



    inner class addSort2() : BottomPopupView(this) {
        override fun getImplLayoutId(): Int {
            return R.layout.sort_add
        }

        override fun onCreate(){
            super.onCreate()
            add_button.setOnClickListener {
                val sortName = sort_title_input.text.toString()
                val sortBody = sort_body_input.text.toString()

                var database = AppDatabase.getDatabase(MyApplication.context)
                var userdao: UserDao = database.userDao();
                var workDao = database.WorkDao()

                val userid = userdao.selectAcUser().userId
                var work1: Work? = Work(userid, Parentid.toInt(), 1, sortName, sortBody, null, null)
                workDao.insertWork(work1)
                refresh()
                dismiss()
            }
        }
        override fun getMaxHeight(): Int {
            return (XPopupUtils.getScreenHeight(context)*.85f).toInt()
        }
    }

    inner class addWork: CenterPopupView(this){
        override fun getImplLayoutId(): Int {
            return R.layout.work_add
        }
        override fun onCreate(){
            super.onCreate()
            var startTime:Long = -1
            var endTime:Long   = -2

            Log.d("StartTime",startTime.toString())
            Log.d("EndTime",endTime.toString())


            add_button2.setOnClickListener{
                val workName = work_title_input.text.toString()
                val workBody = work_body_input.text.toString()
                startTime = dateTimePickerstart.getMillisecond()
                endTime = dateTimePickerend.getMillisecond()
                if(startTime<endTime) {
                    var database = AppDatabase.getDatabase(MyApplication.context)
                    var userdao: UserDao = database.userDao();
                    var workDao = database.WorkDao()
                    val userid = userdao.selectAcUser().userId
                    var work1: Work? = Work(
                        userid,
                        Parentid.toInt(),
                        0,
                        workName,
                        workBody,
                        startTime,
                        endTime
                    )
                    workDao.insertWork(work1)
                    refresh()
                    dismiss()
                }else{
                    Toast.makeText(context,"开始时间不得大于结束时间",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    fun refresh(){
        Parentid = intent.getStringExtra("ID").toString()
        var sortName = ArrayList<String>()
        var sortBody = ArrayList<String>()
        var sortId   = ArrayList<String>()
        var workstartTime = ArrayList<String>()
        var workendTime   = ArrayList<String>()
        var database= AppDatabase.getDatabase(MyApplication.context)
        var workDao = database.WorkDao()
        var sortDetailList = workDao.selectSon(Parentid.toInt())
        for (i in sortDetailList) {
            sortName.add(i.title!!)
            sortBody.add(i.workbody!!)
            sortId.add(i.workId.toString())
            if(i.startTime!=null && i.endTime!=null) {
                workstartTime.add(i.startTime.toString())
                workendTime.add(i.endTime.toString())
            }else{
                workstartTime.add("no")
                workendTime.add("no")
            }
        }

        val sortsAdapter = context?.let { detailAdapter(this, sortId,sortName, sortBody,workstartTime,workendTime) }
        recycleView2.adapter = sortsAdapter
        recycleView2.layoutManager = LinearLayoutManager(context)
    }

    fun deleByOneId(oneId: Int){
        val ids = ArrayList<Int>()
        var database= AppDatabase.getDatabase(MyApplication.context)
        var workDao = database.WorkDao()
        var userDao = database.userDao()
        val userAc = userDao.selectAcUser()
        //先把要删除的一级分类id放入到集合中
        ids.add(oneId)

        //递归的将一级分类下的id也加入到集合中
        getIds(ids, oneId)
        //批量删除集合中的id

        for(i in ids){
            workDao.deleteUserWork((userAc.userId),i)
        }

    }

    //递归方法
    private fun getIds(ids: ArrayList<Int>, oneId: Int) {
        var database= AppDatabase.getDatabase(MyApplication.context)
        var workDao = database.WorkDao()
        //查询二级分类的对象
        val twoSubjects=  workDao.selectSon(oneId)

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (twoSubject in twoSubjects) {
            val id = twoSubject.workId
            ids.add(id)
            //把二级分类的每一个ID，查询它下面的子节点
            getIds(ids, id)
        }
    }
}